package org.example.aicloud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import jakarta.annotation.Resource;
import org.example.aicloud.entity.Answer;
import org.example.aicloud.entity.enums.AiModelEnum;
import org.example.aicloud.entity.enums.AiTypeEnum;
import org.example.aicloud.service.IAnswerService;
import org.example.aicloud.util.AppVariable;
import org.example.aicloud.util.ResultAjax;
import org.example.aicloud.util.SecurityUtil;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/doubao")
public class DoubaoController {

    @Value("${doubao.api-key}")
    private String apiKey;

    @Value("${doubao.model_id}")
    private String modelId;
    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate redisTemplate;
    @RequestMapping("/chat")
    public ResultAjax chat(String question) {
        if (!StringUtils.hasLength(question)) {
            return ResultAjax.error("请输入问题");
        }
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.DOUBAO.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            // 获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResultAjax.error("请勿频繁调用接口！");
            }

            // 1.api-key|调用 url 地址
            ArkService service = ArkService.builder().apiKey(apiKey)
                    .build();
            // 2.构建问题对象
            List<ChatMessage> messages = new ArrayList<>();
            messages.add(ChatMessage.builder()
                    .role(ChatMessageRole.USER)
                    .content(question)
                    .build());
            // 3.创建对象进行对话
            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model(modelId) // 接入点的id（并不是大模型名字）
                    .messages(messages)
                    .build();
            // 4.得到对话的结果
             result = service.createChatCompletion(request)
                    .getChoices()
                    .getFirst() // 获取 AI 大模型生成的第一条消息
                    .getMessage()
                    .getContent().toString();
            //将对话信息存储到数据库
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.DOUBAO.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            answer.setType(AiTypeEnum.CHAT.getValue());
            isSave = answerService.save(answer);
        } catch (Exception e) {

        } finally {
            rLock.unlock();
        }
        if (isSave) {
            return ResultAjax.success(result);
        }

        return ResultAjax.error("请求操作失败，请重试！");
    }

    @PostMapping("/getchatlist")
    public ResultAjax getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int model = AiModelEnum.DOUBAO.getValue();
        int type = AiTypeEnum.CHAT.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model, type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if (list == null) {

            List<Answer> dataList = answerService.list(Wrappers.lambdaQuery(Answer.class)
                    .eq(Answer::getUid, uid)
                    .eq(Answer::getModel,model)
                    .eq(Answer::getType, type)
                    .orderByDesc(Answer::getAid)
            );
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResultAjax.success(dataList);
        } else {
            //System.out.println("触发了redis缓存豆包");
            return ResultAjax.success(list);
        }


    }
}
